<template>
    <div style="height: 100%" class="workspace">
        <el-container ref="listWarp" style="height: 100%">
            <div class="left">
                <div class="title">
                    <div class="area"><span class="line"></span> 区域信息</div>
                </div>
                <div class="statusList">
                    <el-tree
                        :data="treeData"
                        :props="defaultProps"
                        node-key="id"
                        @node-click="handleNodeClick"
                        :default-expanded-keys="defaultExpandedKeys"
                        :current-node-key="currentNodekey"
                        ref="tree"
                        highlight-current
                    ></el-tree>
                </div>
            </div>
            <el-container style="height: 100%; background: #fff; flex: 1" class="right">
                <el-header style="height: auto; padding: 20px 20px 0 20px">
                    <div class="title" style="border: none">
                        <div class="area"><span class="line"></span> 设备信息</div>
                    </div>

                    <div class="selectList">
                        <div class="select">
                            <el-select
                                v-model="searchObj.typeId"
                                placeholder="设备类型"
                                size="small"
                                @change="getTableList()"
                                clearable
                                filterable
                            >
                                <el-option
                                    v-for="item in typeList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                            <el-select
                                v-model="searchObj.statusId"
                                placeholder="设备状态"
                                size="small"
                                @change="getTableList()"
                                clearable
                                filterable
                            >
                                <el-option
                                    v-for="item in statusList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                            <el-input
                                v-model="searchObj.name"
                                @change="getTableList()"
                                size="small"
                                style="width: 160px"
                                placeholder="设备名称"
                            ></el-input>
                        </div>
                        <div class="btns">
                            <div class="add" @click="event('add')">
                                <svg-icon
                                    icon-class="add"
                                    style="font-size: 13px; margin-right: 5px"
                                />新增
                            </div>
                            <div class="edit" @click="event('edit')">
                                <svg-icon
                                    icon-class="edit"
                                    style="font-size: 13px; margin-right: 5px"
                                />

                                编辑
                            </div>
                            <div class="del" @click="event('del')">
                                <svg-icon
                                    icon-class="delete"
                                    style="font-size: 13px; margin-right: 5px"
                                />

                                删除
                            </div>
                            <div class="ma" @click="event('code')">
                                <svg-icon
                                    icon-class="erweima"
                                    style="font-size: 13px; margin-right: 5px"
                                />

                                二维码批量下载
                            </div>
                            <div class="userBatch" @click="event('batchInspectorUser')">
                                批量设置巡检人员
                            </div>
                            <div class="ma" @click="event('export')">
                                <svg-icon
                                    icon-class="daochu"
                                    style="font-size: 13px; margin-right: 5px"
                                />
                                导出
                            </div>
                            <div class="ma" @click="event('evtImport')">
                                <svg-icon
                                    icon-class="daochu"
                                    style="font-size: 13px; margin-right: 5px"
                                />
                                导入
                            </div>
                        </div>
                    </div>
                </el-header>
                <el-main style="height: 100%">
                    <div class="content" style="height: calc(100% - 40px)">
                        <el-table
                            :data="tableData"
                            height="100%"
                            style="width: 100%"
                            border
                            v-loading="loading"
                            highlight-current-row
                            @row-dblclick="tableDbEdit"
                            @current-change="evtTableRowChange"
                            @selection-change="handleSelectionChange"
                            ref="dataListTable"
                        >
                            <el-table-column type="selection" width="55" fixed="left">
                            </el-table-column>
                            <el-table-column
                                type="index"
                                width="50"
                                label="序号"
                                fixed="left"
                            ></el-table-column>
                            <el-table-column
                                prop="name"
                                label="设备名称"
                                width="120"
                                fixed="left"
                            ></el-table-column>
                            <el-table-column
                                prop="buildingName"
                                label="巡检人员"
                                minWidth="340px"
                                fixed="left"
                            >
                                <template slot-scope="scope">
                                    <div style="display: flex">
                                        <div class="users">
                                            <div
                                                v-for="(item, index) in scope.row.inspectorUser"
                                                :key="item.id"
                                                class="user-item"
                                            >
                                                {{ item.userName }}
                                                <svg-icon
                                                    icon-class="close"
                                                    style="font-size: 13px; margin-right: 3px"
                                                    @click="delUser(item, scope.row)"
                                                />
                                            </div>
                                        </div>
                                        <div class="addArea" @click="addUser(scope.row, '1')">
                                            <span style="margin-right: 5px">+</span>新增
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="typeName" label="设备类型" width="98">
                            </el-table-column>
                            <el-table-column
                                prop="statusName"
                                label="状态"
                                width="85"
                            ></el-table-column>
                            <el-table-column
                                prop="model"
                                label="型号/规格"
                                width="100px"
                            ></el-table-column>
                            <el-table-column
                                prop="parameter"
                                label="设备参数"
                                width="100px"
                            ></el-table-column>
                            <el-table-column
                                prop="address"
                                label="使用地点"
                                width="95px"
                            ></el-table-column>
                            <el-table-column
                                prop="startYear"
                                label="投入使用年份"
                                width="105px"
                            ></el-table-column>
                            <el-table-column
                                prop="lessYear"
                                label="最低设备年限"
                                width="105px"
                            ></el-table-column>
                            <el-table-column
                                prop="factory"
                                label="生产厂家"
                                width="95px"
                            ></el-table-column>
                            <el-table-column
                                prop="makeDate"
                                label="生产日期"
                                width="95px"
                            ></el-table-column>
                            <el-table-column
                                prop="supplier"
                                label="采购供应商"
                                width="95px"
                            ></el-table-column>
                            <el-table-column
                                prop="buyDate"
                                label="采购日期"
                                width="95px"
                            ></el-table-column>
                            <el-table-column prop="pic" label="实物照片" width="95px">
                                <template slot-scope="scope">
                                    <el-image
                                        v-if="scope.row.picList.length > 0"
                                        style="width: 40px; height: 40px"
                                        :src="scope.row.picList[0]"
                                        :preview-src-list="scope.row.picList"
                                    >
                                    </el-image> </template
                            ></el-table-column>
                            <el-table-column prop="nameplate" label="设备铭牌照片" width="105px">
                                <template slot-scope="scope">
                                    <el-image
                                        style="width: 40px; height: 40px"
                                        v-if="scope.row.nameplate"
                                        :src="scope.row.nameplateList[0]"
                                        :preview-src-list="scope.row.nameplateList"
                                    >
                                    </el-image> </template
                            ></el-table-column>

                            <el-table-column
                                label="操作"
                                width="180px"
                                align="center"
                                fixed="right"
                            >
                                <template slot-scope="scope">
                                    <div
                                        style="color: #00b38b; cursor: pointer"
                                        @click="repair(scope.row)"
                                    >
                                        维修维护记录
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-footer style="height: 45px; background-color: #fff" class="page-footer">
                            <el-pagination
                                style="padding-top: 10px"
                                background
                                layout="prev, pager, next,jumper,total,sizes"
                                @size-change="evtPageSizeChange"
                                @current-change="evtPageCurrentChange"
                                :current-page.sync="currentPage"
                                :page-sizes="[20, 50, 100, 500]"
                                :total="totalRows"
                            ></el-pagination>
                        </el-footer>
                    </div>
                </el-main>
            </el-container>
        </el-container>

        <!-- 新增区域-->
        <el-dialog
            :visible.sync="dialogFormVisible"
            :close-on-click-modal="false"
            @close="evtDialogClose"
            lock-scroll
            title="设备信息"
            width="762px"
        >
            <div v-loading="addloading">
                <div class="win-warp" style="height: 530px">
                    <el-form
                        :model="form"
                        :rules="addRules"
                        ref="addForm"
                        label-position="top"
                        size="small"
                    >
                        <el-row class="row-bg" :gutter="22">
                            <el-col :span="12">
                                <el-form-item label="设备名称" prop="name">
                                    <el-input
                                        ref="name"
                                        maxlength="30"
                                        v-model="form.name"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="设备类型" prop="typeId">
                                    <el-select
                                        v-model="form.typeId"
                                        placeholder="请选择"
                                        style="width: 100%"
                                        @change="typeChange"
                                        clearable
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in typeList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="设备状态" prop="statusId">
                                    <el-select
                                        v-model="form.statusId"
                                        placeholder="请选择"
                                        style="width: 100%"
                                        @change="statusChange"
                                        clearable
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in statusList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="型号/规格" prop="model">
                                    <el-input v-model="form.model" placeholder="请输入"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="设备参数" prop="parameter">
                                    <el-input
                                        ref="name"
                                        maxlength="30"
                                        v-model="form.parameter"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="使用地点" prop="address">
                                    <el-input
                                        placeholder="请输入"
                                        v-model="form.address"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="投入使用年份" prop="startYear">
                                    <el-input
                                        v-model="form.startYear"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="最低设备使用年限" prop="lessYear">
                                    <el-input
                                        v-model="form.lessYear"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="生产厂家" prop="factory">
                                    <el-input
                                        v-model="form.factory"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="生产日期" prop="makeDate">
                                    <el-date-picker
                                        style="width: 100%"
                                        v-model="form.makeDate"
                                        type="date"
                                        format="yyyy-MM-dd"
                                        value-format="yyyy-MM-dd"
                                        placeholder="请选择日期"
                                        size="small"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="采购供应商" prop="supplier">
                                    <el-input
                                        v-model="form.supplier"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="采购日期" prop="buyDate">
                                    <el-date-picker
                                        style="width: 100%"
                                        v-model="form.buyDate"
                                        type="date"
                                        format="yyyy-MM-dd"
                                        value-format="yyyy-MM-dd"
                                        placeholder="请选择日期"
                                        size="small"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="巡检项目" prop="checkPoint">
                                    <el-input
                                        v-model="form.checkPoint"
                                        type="textarea"
                                        :rows="2"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    :label="'实物照片(' + fileListPic.length + '/6)'"
                                    prop="buyDate"
                                >
                                    <el-upload
                                        class="avatar-uploader"
                                        action="/api/file/upload"
                                        list-type="picture-card"
                                        :data="Imgdata"
                                        accept="image/*"
                                        :headers="headers"
                                        :on-preview="handlePreview"
                                        :before-upload="beforeAvatarUpload"
                                        :on-remove="handleRemove"
                                        :on-success="handleAvatarSuccess"
                                        :before-remove="beforeRemove"
                                        multiple
                                        :limit="6"
                                        :on-exceed="handleExceed"
                                        :file-list="fileListPic"
                                    >
                                        <i class="el-icon-plus"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    prop="buyDate"
                                    :label="'设备铭牌照片(' + fileListNameplate.length + '/6)'"
                                >
                                    <el-upload
                                        class="avatar-uploader"
                                        action="/api/file/upload"
                                        list-type="picture-card"
                                        :data="Imgdata"
                                        accept="image/*"
                                        :headers="headers"
                                        :on-preview="handlePreview"
                                        :before-upload="beforeAvatarUpload"
                                        :on-remove="handleRemove1"
                                        :on-success="handleAvatarSuccess1"
                                        :before-remove="handleRemove1"
                                        multiple
                                        :limit="6"
                                        :on-exceed="handleExceed"
                                        :file-list="fileListNameplate"
                                    >
                                        <i class="el-icon-plus"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
                    <el-button
                        @click="addBtn()"
                        type="primary"
                        size="small"
                        style="background: #00b38b; border: none"
                        >确定</el-button
                    >
                </div>
            </div>
        </el-dialog>

        <!-- 新增用户 -->
        <el-dialog
            :visible.sync="dialogFormVisibleUser"
            :close-on-click-modal="false"
            @close="evtDialogClose"
            lock-scroll
            title="添加"
            width="550px"
        >
            <div v-loading="addloading">
                <div class="win-warp" style="height: 300px">
                    <el-input
                        v-model="username"
                        placeholder="请输入名称/账号查找"
                        size="small"
                        style="margin-bottom: 10px"
                        @change="getUserList"
                    ></el-input>
                    <el-table
                        :data="userList"
                        height="250px"
                        style="width: 100%"
                        border
                        tooltip-effect="light"
                        highlight-current-row
                        ref="userTable"
                        @selection-change="userSelectionChange"
                    >
                        <el-table-column type="selection" width="55"> </el-table-column>
                        <el-table-column type="index" width="50" label="序号"></el-table-column
                        ><el-table-column prop="name" label="姓名"></el-table-column
                        ><el-table-column prop="account" label="账号"></el-table-column
                    ></el-table>
                </div>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisibleUser = false" size="small">取 消</el-button>
                    <el-button
                        @click="addUserConfirm()"
                        type="primary"
                        size="small"
                        style="background: #00b38b; border: none"
                        >确定</el-button
                    >
                </div>
            </div>
        </el-dialog>
        <!-- 二维码 -->
        <el-dialog
            :visible.sync="dialogCode"
            :close-on-click-modal="false"
            @close="evtDialogClose"
            lock-scroll
            title="二维码"
            width="620px"
        >
            <div v-loading="addloading">
                <div class="win-warp qrBox" style="height: 420px" id="print">
                    <div v-for="(item, index) in codeList" :key="index" class="qrItemBox">
                        <div class="qr-code" ref="qrCode"></div>
                        <div>{{ item.name }}</div>
                    </div>
                </div>
                <div class="dialog-footer">
                    <el-button size="small" v-print="printObj">打印</el-button>
                    <el-button
                        @click="downImg()"
                        type="primary"
                        size="small"
                        style="background: #00b38b; border: none"
                        >下载</el-button
                    >
                </div>
            </div>
        </el-dialog>
        <dialogTable :maintenanceTypeList="maintenanceTypeList" ref="dialogTableRef" />
        <export-excel
            ref="exportExcel"
            :sheet-name="sheetName"
            :file-name="exportFileName"
            extend="export"
            :columns="columns"
            :rows="totalRows"
            :query="search"
            :export-api="exportApi"
        />
        <!--导入数据窗口-->
        <el-dialog
            :title="'导入用户基本数据'"
            :visible.sync="importDialog"
            :close-on-click-modal="false"
            lock-scroll
            append-to-body
            destroy-on-close
            fullscreen
            class="fullscreenDialog"
        >
            <import-excel
                ref="importDialog"
                :api-import-data-validate="apiImportDataValidate"
                :api-import-data="apiImportData"
                :import-query-filed="importQueryFiled"
                :import-target-data="importTargetData"
                :import-type="2"
                @finish="evtImportFinish"
                @close="
                    () => {
                        this.importDialog = false
                        this.$refs.importDialog.clearData
                    }
                "
            ></import-excel>
        </el-dialog>
    </div>
</template>

<script>
import { equipmentApi } from '@/api/patrol/equipment'
import Token from '@/itsoftUI/auth/token.js'
import dialogTable from './dialogTable'
import exportExcel from '@/itsoftUI/components/exportExcel/exportExcel'
import importExcel from '@/itsoftUI/components/importExcel/importExcel'

import { apiIndex } from '@/api/accommodation/index'

import QRCode from 'qrcodejs2'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
export default {
    components: {
        dialogTable,
        exportExcel,
        importExcel,
    },
    watch: {
        areaName: {
            handler() {
                // this.exportFileName = this.areaName + this.exportFileName;
                // this.sheetName = this.areaName + this.sheetName;
                // console.log('====================================');
                // console.log( this.sheetName);
                // console.log('====================================');
            },
        },
    },
    data() {
        return {
            //导入
            importDialog: false,
            //导入数据验证方法
            apiImportDataValidate: equipmentApi.ImportDeviceInfoValidate,
            //导入数据验证方法
            apiImportData: equipmentApi.ImportDeviceInfo,
            importQueryFiled: {},
            importTargetData: [],
            exportFileName: '区域设备信息表',
            sheetName: '',
            exportApi: equipmentApi.List,
            username: '',
            columns: [
                {
                    prop: 'name',
                    label: '设备名称',
                },
                {
                    prop: 'typeName',
                    label: '设备类型',
                },
                {
                    prop: 'statusName',
                    label: '类型',
                },
                {
                    prop: 'model',
                    label: '型号/规格',
                },
                {
                    prop: 'parameter',
                    label: '设备参数',
                },
                {
                    prop: 'address',
                    label: '使用地点',
                },
                {
                    prop: 'startYear',
                    label: '投入使用年份',
                },
                {
                    prop: 'lessYear',
                    label: '最低设备年限',
                },
                {
                    prop: 'factory',
                    label: '生产厂家',
                },
                {
                    prop: 'makeDate',
                    label: '生产日期',
                },
                {
                    prop: 'supplier',
                    label: '采购供应商',
                },
                {
                    prop: 'buyDate',
                    label: '采购日期',
                },
            ],
            areaName: '',
            printObj: {
                id: 'print', //打印的ID，与打印内容的盒子id一致
                popTitle: '区域信息二维码', //打印的标题
            },

            loading: false,
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            search: [],
            searchObj: {
                name: '',
                typeId: '',
                statusId: '',
            },
            totalRows: 0,
            pageSize: 20,
            currentPage: 1,
            typeList: [], // 设备类型
            statusList: [], // 设备状态
            maintenanceTypeList: [], // 维护类型
            multipleSelection: [],
            tableData: [],
            currentRow: null,
            defaultExpandedKeys: [], // 默认展开
            codeList: [],
            currentNodekey: '', // 默认选中
            dialogFormVisible: false,
            dialogFormVisibleUser: false,
            addloading: false,
            dialogCode: false,
            userSelection: [],
            inspectorUser: [],
            managerUser: [],
            userList: [],
            saveType: '1', // 1单个 2批量
            form: {
                name: '',
            },

            addRules: {
                name: [
                    {
                        required: true,
                        message: '请填写设备名称',
                        trigger: 'blur',
                    },
                ],
                typeId: [
                    {
                        required: true,
                        message: '请选择设备类型',
                        trigger: 'blur',
                    },
                ],
                statusId: [
                    {
                        required: true,
                        message: '请填写设备状态',
                        trigger: 'blur',
                    },
                ],
            },
            // 图片
            fileListPic: [], // 实物照片
            fileListNameplate: [], // 设备铭牌照片
            Imgdata: {
                system: 'newRepair',
            },
            headers: {
                Token: '',
                TokenKey: '',
            },
        }
    },
    methods: {
        //获取导入字段
        funImportList() {
            let search = [
                {
                    andOr: 'and',
                    searchField: 'useWay',
                    operator: '=',
                    searchValue: 'stayInfo',
                },
            ]
            equipmentApi.ImportList([], 'orderNum asc').then((res) => {
                this.importTargetData = res.data
            })
        },
        // 维护维修记录
        repair(row) {
            this.$refs.dialogTableRef.dialogTableVisible = true
            setTimeout(() => {
                this.$refs.dialogTableRef.searchObj.deviceId = row.id
                this.$refs.dialogTableRef.getTableList()
            }, 100)
        },
        // 图片批量下载到本地
        getImgArrayBuffer(url) {
            let _this = this
            return new Promise((resolve, reject) => {
                //通过请求获取文件blob格式
                let xmlhttp = new XMLHttpRequest()
                xmlhttp.open('GET', url, true)
                xmlhttp.responseType = 'blob'
                xmlhttp.onload = function () {
                    if (this.status == 200) {
                        resolve(this.response)
                    } else {
                        reject(this.status)
                    }
                }
                xmlhttp.send()
            })
        },
        // 图片批量下载
        downImg() {
            this.$confirm('网速太慢或图片太多时，请耐心等待~', '温馨提示', {
                confirmButtonText: '我知道了，开始下载',

                showCancelButton: false,
                type: 'success',
            }).then(() => {
                let _this = this
                let zip = new JSZip()
                let cache = {}
                let promises = []
                let images = this.imgsList
                images.forEach((item, index) => {
                    const promise = _this.getImgArrayBuffer(item).then((data) => {
                        //解决之前ios 文件没有后缀名，电脑打不开的问题，默认加上png后缀，没有该问题的可去掉 这部分代码
                        let file = item.split('/')[item.split('/').length - 1]
                        let fileType = file.split('.')
                        let filename
                        if (fileType.length == 1) {
                            filename = _this.codeList[index].name + '.png' //判断是ios没有后缀名的文件
                        } else {
                            filename = _this.codeList[index].name
                        }
                        // --end
                        zip.file(filename, data, {
                            binary: true,
                        })
                        cache[filename] = data
                    })
                    promises.push(promise)
                })
                Promise.all(promises)
                    .then(() => {
                        zip.generateAsync({
                            type: 'blob',
                        }).then((content) => {
                            FileSaver.saveAs(content, '二维码')
                        })
                    })
                    .catch((res) => {
                        _this.$message.error('文件压缩失败')
                    })
            })
        },

        CanvasToImage(canvas) {
            //从canvas中提取图片image，新建image对象
            var image = new Image()
            // canvas.toDataURL 返回Base64编码的URL
            image.src = canvas.toDataURL('image/jpg')
            return image
        },
        /* 创建二维码 */
        creatQrCode() {
            this.imgsList = []

            this.codeList.forEach((e, index) => {
                new QRCode(this.$refs.qrCode[index], {
                    text: `${this.$itsoftUI.config.inspectionUrl}?id=${e.id}`, // 二维码的内容 // 二维码的内容
                    width: 120,
                    height: 120,
                    colorDark: '#000',
                    colorLight: '#fff',
                    correctLevel: QRCode.CorrectLevel.H,
                })
            })
            let canvasobjList = Array.prototype.slice.call(document.getElementsByTagName('canvas'))

            canvasobjList.forEach((e) => {
                this.imgsList.push(this.CanvasToImage(e).src)
            })
        },
        // 创建二维码
        downCode(row) {
            this.dialogCode = true
            this.codeList = [row]
            setTimeout(() => {
                this.creatQrCode()
            }, 100)
        },
        // 获取全部区域生成web二维码
        getCodeList() {
            this.addloading = true
            this.setSearchData()
            equipmentApi
                .codeList(JSON.stringify(this.search), '', 'createTime desc')
                .then((res) => {
                    this.codeList = res.data
                    this.addloading = false
                    setTimeout(() => {
                        this.creatQrCode()
                    }, 100)
                    this.loading = false
                })
        },
        // 删除用户
        delUser(item, row) {
            this.$confirm('确定要删除当前选中的用户吗？', '删除', {
                distinguishCancelAndClose: true,
                confirmButtonText: '删除',
                cancelButtonText: '放弃删除',
            })
                .then(() => {
                    equipmentApi.deleteDeviceUser(row.id, item.userId).then((res) => {
                        this.$message.success('删除成功')
                        this.getTableList()
                    })
                })
                .catch(() => {})
        },
        // 选中用户
        userSelectionChange(val) {
            this.userSelection = val
        },
        // 添加用户
        addUser(row, type) {
            this.currentRow = row
            this.dialogFormVisibleUser = true
            this.type = type
            this.inspectorUser = row.inspectorUser ? row.inspectorUser : []
            this.managerUser = row.managerUser ? row.managerUser : []
            this.saveType = '1'
            this.getUserList()
        },
        // 获取用户
        getUserList() {
            this.addloading = true
            let search = [
                {
                    andOr: 'and',
                    searchField: 'schoolcode',
                    operator: '=',
                    searchValue: this.$itsoftUI.config.schoolCode,
                },
                {
                    andOr: 'and',
                    searchField: 'systemcode',
                    operator: '=',
                    searchValue: 'newRepair',
                },
            ]
            if (this.username) {
                search.push({
                    andOr: 'and',
                    searchField: 'account/name',
                    operator: 'like',
                    searchValue: this.username,
                })
            }
            equipmentApi.userList(JSON.stringify(search)).then((res) => {
                let users = [...this.inspectorUser, ...this.managerUser]

                let list = res.data.filter((item) => !users.some((ele) => ele.userId === item.id))
                this.userList = list
                this.addloading = false
            })
        },
        //保存
        addUserConfirm() {
            if (this.saveType === '1') {
                if (this.userSelection.length === 0) {
                    this.$message.error('请选择用户')
                    return false
                }

                let list = []
                this.userSelection.forEach((item) => {
                    list.push({
                        deviceId: this.currentRow.id,
                        type: this.type,
                        userId: item.id,
                        userName: item.name,
                    })
                })
                this.addloading = true
                equipmentApi
                    .saveDeviceUser(JSON.stringify(list))
                    .then((e) => {
                        this.dialogFormVisibleUser = false
                        this.getTableList()
                        this.$message.success('添加成功')
                        this.addloading = false
                    })
                    .catch(() => {
                        this.dialogFormVisibleUser = false
                        this.addloading = false
                    })
            } else if (this.saveType === '2') {
                this.addloading = true
                let ids = this.multipleSelection.map((e) => e.id)
                equipmentApi
                    .batchSavedeviceUser(
                        ids.toString(),
                        this.type,
                        JSON.stringify(
                            this.userSelection.map((e) => {
                                return {
                                    userId: e.id,
                                    userName: e.name,
                                }
                            })
                        )
                    )
                    .then((res) => {
                        this.dialogFormVisibleUser = false
                        this.getTableList()
                        this.$message.success('添加成功')
                        this.addloading = false
                    })
                    .catch(() => {
                        this.dialogFormVisibleUser = false
                        this.addloading = false
                        this.$refs.dataListTable.clearSelection()
                    })
            }
        },
        addBtn() {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.addloading = true
                    this.form.regionId = this.currentNodekey
                    equipmentApi.save(this.form).then((res) => {
                        this.addloading = false
                        if (res.status == 'success') {
                            this.$message.success('提交成功')
                            this.dialogFormVisible = false
                            this.addloading = false
                            this.$refs.addForm.clearValidate()
                            this.$refs.addForm.resetFields()
                            this.getTableList()
                        }
                    })
                } else {
                    //   this.addloading = false;
                    return false
                }
            })
        },
        evtDialogClose() {
            this.form = {}
            this.codeList = []
            this.fileListPic = []
            this.fileListNameplate = []
            if (this.$refs.qrCode && this.$refs.qrCode.length > 0) {
                this.$refs.qrCode.forEach((e) => {
                    e.innerHTML = ''
                })
            }
        },
        // 组装条件
        setSearchData() {
            this.search = []
            for (const key in this.searchObj) {
                const item = this.searchObj[key]
                if (item) {
                    if (key === 'typeId' || key === 'statusId' || key === 'regionId') {
                        this.search.push({
                            andOr: 'and',
                            searchField: key,
                            operator: '=',
                            searchValue: item,
                        })
                    }
                    if (key === 'name') {
                        this.search.push({
                            andOr: 'and',
                            searchField: key,
                            operator: 'like',
                            searchValue: item,
                        })
                    }
                }
            }
        },
        // 区域事件
        event(key) {
            switch (key) {
                case 'add':
                    this.dialogFormVisible = true
                    break
                case 'edit':
                    if (!this.currentRow) {
                        this.$message.error('请选中需要编辑的数据行')
                        return
                    }
                    this.getDetail()
                    break
                case 'del':
                    if (this.multipleSelection.length === 0) {
                        this.$message.error('请选中要删除的数据')
                        return
                    }
                    this.del()
                    break
                case 'code':
                    this.dialogCode = true
                    this.getCodeList()
                    break
                case 'batchInspectorUser':
                    if (this.multipleSelection.length === 0) {
                        this.$message.error('请选中要设置的数据')
                        return false
                    }
                    this.dialogFormVisibleUser = true
                    this.type = '1'
                    this.saveType = '2'
                    this.getUserList()
                    break
                case 'export':
                    this.$refs.exportExcel.exportOpen()
                    break
                case 'evtImport':
                    this.importDialog = true
                    break
                default:
                    break
            }
        },
        //导入完成
        evtImportFinish() {
            this.importDialog = false
            this.getTableList()
        },
        getDetail() {
            this.dialogFormVisible = true
            this.addloading = true
            equipmentApi
                .Get(this.currentRow.id)
                .then((res) => {
                    this.form = res.data
                    this.addloading = false
                    this.fileListPic = this.form.pic
                        ? this.form.pic.split(',').map((e) => {
                              return {
                                  url: this.$itsoftUI.config.fileServer + e,
                              }
                          })
                        : []
                    this.fileListNameplate = this.form.nameplate
                        ? this.form.nameplate.split(',').map((e) => {
                              return {
                                  url: this.$itsoftUI.config.fileServer + e,
                              }
                          })
                        : []
                })
                .catch(() => {
                    this.addloading = false
                })
        },
        // 删除
        del() {
            this.$confirm('确定要删除当前选中的数据吗？', '删除', {
                distinguishCancelAndClose: true,
                confirmButtonText: '删除',
                cancelButtonText: '放弃删除',
            })
                .then(() => {
                    let idList = []
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        idList.push(this.multipleSelection[i].id)
                    }
                    var ids = idList.join(',')
                    equipmentApi.Del(ids).then((res) => {
                        if ((res.status = 'success')) {
                            this.$message.success('删除成功')
                            this.getTableList()
                        }
                    })
                })
                .catch(() => {
                    this.$refs.dataListTable.clearSelection()
                })
        },
        // 获取表格数据
        getTableList() {
            this.loading = true
            this.setSearchData()
            let page = {
                pageIndex: this.currentPage,
                pageSize: this.pageSize,
            }
            equipmentApi
                .List(JSON.stringify(page), JSON.stringify(this.search), '', 'createTime desc')
                .then((res) => {
                    this.tableData = res.data.rows
                    this.tableData.forEach((item) => {
                        item.picList = item.pic
                            ? item.pic.split(',').map((e) => {
                                  return this.$itsoftUI.config.fileServer + e
                              })
                            : []
                        item.nameplateList = item.nameplate
                            ? item.nameplate.split(',').map((e) => {
                                  return this.$itsoftUI.config.fileServer + e
                              })
                            : []
                    })
                    this.totalRows = res.data.total
                    this.loading = false
                })
        },
        evtPageSizeChange(val) {
            //每页数量
            this.pageSize = val
            this.getTableList()
        },
        evtPageCurrentChange(val) {
            //分页
            this.currentPage = val
            this.getTableList()
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        tableDbEdit(currentRow) {
            //双击行
            this.currentRow = currentRow
            this.getDetail()
        },
        evtTableRowChange(currentRow) {
            //单选行
            this.currentRow = currentRow
        },
        // 获取区域树
        getTreeData() {
            equipmentApi.getRegionTree().then((res) => {
                this.treeData = res.data
                if (this.treeData.length > 0) {
                    this.defaultExpandedKeys = [this.treeData[0].id]

                    if (this.treeData[0].children.length > 0) {
                        this.currentNodekey = this.treeData[0].children[0].id
                        this.searchObj.regionId = this.treeData[0].children[0].id
                        this.areaName = this.treeData[0].children[0].name
                        this.$refs.exportExcel.inputFileName =
                            this.areaName + this.$refs.exportExcel.inputFileName

                        this.getTableList()
                        //把当前选择的key设置到el-tree中
                        this.$nextTick(function () {
                            this.$refs.tree.setCurrentKey(this.currentNodekey)
                        })
                    }
                }
            })
        },
        // 单机
        handleNodeClick(data) {
            this.$refs.exportExcel.inputFileName = '区域信息二维码'
            if (data.type === '2') {
                this.currentNodekey = data.id
                this.searchObj.regionId = data.id
                this.areaName = data.name
                this.$refs.exportExcel.inputFileName =
                    this.areaName + this.$refs.exportExcel.inputFileName

                this.getTableList()
            } else {
                this.$message.warning('请点击二级区域进行筛选')
            }
        },
        typeChange() {
            this.form.typeName = this.typeList.find((e) => e.id === this.form.typeId).name
        },
        statusChange() {
            this.form.statusName = this.statusList.find((e) => e.id === this.form.statusId).name
        },
        // 数据字典
        getSystemData(val) {
            let search = [
                {
                    andOr: 'and',
                    searchField: 'dictTypeId',
                    operator: '=',
                    searchValue: val,
                },
            ]
            equipmentApi.systemDictData(JSON.stringify(search)).then((res) => {
                switch (val) {
                    case '2':
                        this.statusList = res.data
                        break
                    case '3':
                        this.typeList = res.data
                        break
                    case '1':
                        this.maintenanceTypeList = res.data
                        break
                    default:
                        break
                }
            })
        },
        //放大查看图片
        handlePreview(file) {
            var newwin = window.open()
            newwin.document.write('<img src=' + file.url + ' />')
        },
        beforeAvatarUpload(file) {
            //文件上传之前调用做一些拦截限制
            this.headers.Token = Token.getToken()
            this.headers.TokenKey = Token.getTokenKey()
            const isJPG = true
            // const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        // 实物照片
        handleRemove(file, fileList) {
            let imgArr = []
            this.fileListPic.forEach((item, key) => {
                if (item.url == file.url) {
                    this.fileListPic.splice(key, 1)
                }
            })
            this.fileListPic.forEach((item) => {
                let str = item.url.replace(this.$itsoftUI.config.fileServer, '')
                imgArr.push(str)
            })
            this.form.pic = imgArr.join(',')
        },
        // 设备铭牌照片
        handleRemove1(file, fileList) {
            let imgArr = []
            this.fileListNameplate.forEach((item, key) => {
                if (item.url == file.url) {
                    this.fileListNameplate.splice(key, 1)
                }
            })
            this.fileListNameplate.forEach((item) => {
                let str = item.url.replace(this.$itsoftUI.config.fileServer, '')
                imgArr.push(str)
            })
            this.form.nameplate = imgArr.join(',')
        },
        handleAvatarSuccess(file, fileList) {
            //实物照片
            let imgArr = []
            let obj = {}
            obj.name = file.data.name
            obj.url = this.$itsoftUI.config.fileServer + file.data.path
            this.fileListPic.push(obj)
            this.fileListPic.forEach((item) => {
                let str = item.url.replace(this.$itsoftUI.config.fileServer, '')
                imgArr.push(str)
            })
            this.form.pic = imgArr.join(',')
        },
        handleAvatarSuccess1(file, fileList) {
            //实物照片
            let imgArr = []
            let obj = {}
            obj.name = file.data.name
            obj.url = this.$itsoftUI.config.fileServer + file.data.path
            this.fileListNameplate.push(obj)
            this.fileListNameplate.forEach((item) => {
                let str = item.url.replace(this.$itsoftUI.config.fileServer, '')
                imgArr.push(str)
            })
            this.form.nameplate = imgArr.join(',')
        },
        beforeRemove() {
            return this.$confirm(`确定移除 ？`)
        },
        handleExceed() {
            this.$message.error('已达到上传最大数量')
        },
    },
    created() {
        this.getTreeData()
        this.getSystemData('2')
        this.getSystemData('3')
        this.getSystemData('1')
        this.funImportList()
    },
}
</script>

<style lang="scss" scoped>
.users {
    display: flex;
    align-items: center;
    column-gap: 5px;
    row-gap: 5px;
    margin-right: 5px;
    flex-wrap: wrap;
    .user-item {
        cursor: pointer;
        height: 24px;
        background: #f2f3f5;
        border-radius: 2px 2px 2px 2px;
        opacity: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        column-gap: 6px;
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #1d2129;
        padding: 6px;
    }
}
.addArea {
    width: 50px;
    font-size: 14px;
    font-family: Alibaba PuHuiTi 2-55 Regular, Alibaba PuHuiTi 20;
    font-weight: normal;
    color: #00b38b;
    cursor: pointer;
    word-break: keep-all;
}
@media print {
    #print {
        padding-top: 35px;
        display: flex;
        column-gap: 60px;
        row-gap: 20px;
        flex-wrap: wrap;
        justify-content: center;
        .qrItemBox {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #1d2129;
            row-gap: 5px;
        }
    }
}
.qrBox {
    display: flex;
    column-gap: 60px;
    row-gap: 20px;
    flex-wrap: wrap;
    justify-content: center;
    .qrItemBox {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: #1d2129;
        row-gap: 5px;
    }
}
.workspace {
    //::v-deep .el-tree-node__content {
    //   height: 35px;
    //   &:hover {
    //     // background: #fff !important;
    //   }
    // }
    //::v-deep .el-tree--highlight-current,
    // .el-tree-node,
    // .is-current > .el-tree-node__content {
    //   // background: #e5f7f3 !important;
    //   // }
    // }
    ::v-deep .el-form--label-top .el-form-item__label {
        padding: 0 !important;
    }
    .title {
        display: flex;
        align-items: center;

        font-size: 16px;
        font-family: Alibaba PuHuiTi 2-65 Medium, Alibaba PuHuiTi 20;
        font-weight: normal;
        color: #1d2129;
        justify-content: space-between;
        align-items: center;
        .area {
            display: flex;
            column-gap: 8px;
            align-items: center;
        }
        .addArea {
            font-size: 14px;
            font-family: Alibaba PuHuiTi 2-55 Regular, Alibaba PuHuiTi 20;
            font-weight: normal;
            color: #00b38b;
        }
        .line {
            display: inline-block;
            width: 3px;
            height: 15px;
            background: #00b38b;
        }
        padding-bottom: 16px;
        border-bottom: 1px solid #eeeeee;
    }
    .left {
        width: 238px;
        background: #fff;
        margin-right: 10px;
        padding: 20px;

        .statusList {
            height: calc(100% - 30px);
            overflow: auto;
            margin-top: 10px;
            .item {
                font-size: 14px;
                height: 42px;
                background: #fff;
                line-height: 42px;
                cursor: pointer;
                padding: 0 10px;
                display: flex;
                justify-content: space-between;
            }
            .activeItem {
                background: #e5f7f3;
                border-radius: 2px 2px 2px 2px;
                color: #00b38b;
            }
        }
    }
    .right {
        // padding: 20px;
        .selectList {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            row-gap: 10px;
            .select {
                display: flex;
                column-gap: 10px;
            }
            .btns {
                display: flex;
                column-gap: 12px;
                div {
                    height: 32px;
                    border-radius: 2px 2px 2px 2px;
                    font-size: 14px;
                    font-family: PingFang SC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #ffffff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 1px 15px;
                    cursor: pointer;
                }
                .add {
                    background: #00b38b;
                }
                .edit {
                    background: #3d83ff;
                }
                .del {
                    background: #ff5c5e;
                }
                .ma {
                    background: #3d83ff;
                }
                .userBatch,
                .user {
                    color: #1d2129;
                    border: 1px solid #c9cdd4;
                }
            }
        }
    }
}
</style>
